import { Button, Form, Input, Select, Checkbox, message } from 'antd'
import services from '@/services'
import { type BaseCodeRule, CodeRuleType, CodeScope } from '@/services/features/code-join-groups'
import { type EditingRule } from '.'
import './EditRule.module.less'

export default function EditRule(props: {
  rule: EditingRule
  goPrev: (rule: EditingRule) => void
  onFinish: () => void
}) {
  const { rule: initialRule, goPrev, onFinish } = props
  const [form] = Form.useForm<EditingRule>()

  const onGoPrev = useCallback(() => {
    const values = form.getFieldsValue()
    goPrev(values)
  }, [form, goPrev])

  const [submitting, setSubmitting] = useState(false)
  const onSubmit = useCallback(
    async (values: BaseCodeRule) => {
      setSubmitting(true)
      const res = await services.features.codeJoinGroups.addOrUpdate({
        id: initialRule.id,
        ...values,
      })
      setSubmitting(false)

      if (res.success) {
        void message.success('保存成功！')
        onFinish()
      } else {
        void message.warning(`保存失败：${res.error}`)
      }
    },
    [initialRule, onFinish],
  )

  return <Form form={form} initialValues={initialRule} labelCol={{ span: 6 }} onFinish={onSubmit}>
    <div styleName="fields">
      <Form.Item hidden name="enable">
        <Input />
      </Form.Item>
      <Form.Item hidden name="wxids">
        <Input />
      </Form.Item>
      <Form.Item hidden name="groups">
        <Input />
      </Form.Item>
      <Form.Item hidden name="queue">
        <Input />
      </Form.Item>
      <Form.Item hidden name="queueMemberLimit">
        <Input />
      </Form.Item>

      <Form.Item name="name" label="口令规则名称" rules={[{ required: true }]}>
        <Input maxLength={30} />
      </Form.Item>

      <Form.Item name="type" label="口令匹配模式" rules={[{ required: true }]}>
        <Select>
          <Select.Option value={CodeRuleType.Exact}>精确匹配</Select.Option>
          <Select.Option value={CodeRuleType.Fuzzy}>模糊匹配</Select.Option>
          <Select.Option value={CodeRuleType.Regex}>正则匹配</Select.Option>
        </Select>
      </Form.Item>

      <Form.Item name="keyword" label="口令内容" rules={[{ required: true }]}>
        <Input maxLength={100} />
      </Form.Item>

      <Form.Item
        name="scope"
        label="应用于"
        rules={[{ required: true, message: '请选择应用范围' }]}
      >
        <Checkbox.Group>
          <Checkbox value={CodeScope.External}>客户聊天</Checkbox>
          <Checkbox value={CodeScope.Group}>群聊天</Checkbox>
        </Checkbox.Group>
      </Form.Item>
    </div>

    <footer>
      <Button disabled={submitting} onClick={onGoPrev}>
        上一步
      </Button>
      <Button type="primary" htmlType="submit" loading={submitting}>
        完成
      </Button>
    </footer>
  </Form>
}
